package com.fastloan.safe.mgt.org.controller;

import com.fastloan.safe.core.perms.Licensing;
import com.fastloan.safe.core.util.ManagerKit;
import com.fastloan.safe.mgt.org.model.CmuOrg;
import com.fastloan.safe.mgt.org.service.CmuOrgService;
import com.fastloan.safe.mgt.root.model.CmDefFun;
import com.fastloan.safe.mgt.root.service.CmDefFunService;
import com.fastloan.safe.mgt.sys.service.CmChinaCityService;
import com.fastloan.safe.mgt.sys.service.CmSysFileService;
import com.fastloan.safe.mgt.user.model.CmuUser;
import com.kawins.base.baseabs.BaseController;
import com.kawins.result.ResultEnum;
import com.kawins.result.ResultTo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author rankai
 *         createTime 2017-10-2017/10/18 10:57
 */
@RestController
@RequestMapping("/api/web/cmuOrg")
public class CmuOrgController extends BaseController<CmuOrg> {

    @Autowired
    private CmuOrgService orgService;

    @Autowired
    private CmDefFunService defFunService;

    @Autowired
    private CmChinaCityService chinaCityService;

    @Autowired
    private CmSysFileService sysFileService;

    /**
     * 获取子机构树
     *
     * @return
     */
    @RequestMapping("/pageList/son")
    public ResultTo pageListForSonOrg() {
        return new ResultTo().setData(orgService.selectSonByTop(ManagerKit.getTopOrgId(), true, true));
    }

    /**
     * 机构增加/编辑页面所需数据
     *
     * @return
     */
    @GetMapping("/param/son")
    public ResultTo paramSonOrg(@RequestParam(required = false) String orgId) {
        Map<String, Object> map = new HashMap<>(0);
//        map.put("users", userService.selectBySonAdminNoHasOrg());
        map.put("orgTree", orgService.selectSonByTop(ManagerKit.getOrgId(), true, true));
        if (StringUtils.isBlank(orgId)) {
        } else {
            CmuOrg cmuOrg = adaptService.selectByPrimaryKey(orgId);
            map.put("sonOrg", cmuOrg);
            map.put("city", chinaCityService.selectIdByTree(cmuOrg.getAreaId()));
            map.put("profile", sysFileService.selectByPrimaryKey(cmuOrg.getProfile()));
            map.put("weixinLogo", sysFileService.selectByPrimaryKey(cmuOrg.getWeixinCode()));
            map.put("licenseImg", sysFileService.selectByPrimaryKey(cmuOrg.getLicenseImg()));
        }
        return new ResultTo().setData(map);
    }

    /**
     * 增加子机构
     *
     * @param cmuOrg
     * @return
     */
    @PostMapping("/son")
    public ResultTo insertSonOrg(CmuOrg cmuOrg, @RequestPart("weixin") MultipartFile weixinCode,
                                 @RequestPart("logoFile") MultipartFile logoFile,
                                 @RequestPart(value = "license", required = false) MultipartFile licenseImg) {
        if (logoFile == null || logoFile.getSize() == 0) {
            return new ResultTo(ResultEnum.PARAM_ERROR, "logo不能为空");
        }
        ResultTo resultTo = validBuild(cmuOrg, false);
        if ((int) resultTo.get("code") == ResultEnum.OPERATION_FAILED.getCode()) {
            return resultTo;
        }
        orgService.insertSonOrg(cmuOrg, weixinCode, logoFile, licenseImg);
        return new ResultTo();
    }

    /**
     * 更新子机构
     *
     * @param cmuOrg
     * @return
     */
    @PutMapping("/son")
    public ResultTo updateSonOrg(CmuOrg cmuOrg, @RequestPart("weixin") MultipartFile weixinCode,
                                 @RequestPart("logoFile") MultipartFile logoFile
            , @RequestPart(value = "license",required = false) MultipartFile licenseImg) {
        ResultTo resultTo = validBuild(cmuOrg, true);
        if ((int) resultTo.get("code") == ResultEnum.OPERATION_FAILED.getCode()) {
            return resultTo;
        }
        if (orgService.updateSonOrg(cmuOrg, weixinCode, logoFile, licenseImg)) {
            return new ResultTo();
        }
        return new ResultTo(ResultEnum.OPERATION_FAILED, "没有找到机构管理员角色");
    }

    /**
     * 删除自机构
     * 子
     *
     * @param cmuOrgId
     * @return
     */
    @DeleteMapping("/{cmuOrgId}/son")
    public ResultTo deleteSonOrg(@PathVariable String cmuOrgId) {
        return new ResultTo();
    }


    /**
     * 获取顶级机构列表
     *
     * @return
     */
    @RequestMapping("/pageList/top")
    @RequiresPermissions("all:/web/cmuOrg/pageList/top")
    @Licensing({"add#post:/web/cmuOrg/top", "update#put:/web/cmuOrg/top", "del#delete:/web/cmuOrg/topOrgId/top"})
    public ResultTo pageListForTopOrg() {
        Map<String, Object> map = new HashMap<>();
        map.put("parentId", CmuOrgService.TOP_ORG_PARENT_ID);
        return dataPage("cmuOrgPageList", map);
    }

    /**
     * 获取增加或者更新顶级机构页面数据
     *
     * @param topOrgId
     * @return
     */
    @GetMapping("/param/top")
    @RequiresPermissions(value = {"post:/web/cmuOrg/top", "put:/web/cmuOrg/top"}, logical = Logical.OR)
    public ResultTo paramTopOrg(@RequestParam(required = false) String topOrgId) {
        Map<String, Object> map = new HashMap<>(0);
        map.put("defFunList", defFunService.select(new CmDefFun()
                .setParentId(CmDefFunService.TOP_FUN_PARENT_ID).setIsAdmin(0)));
        if (StringUtils.isBlank(topOrgId)) {
        } else {
            CmuOrg cmuOrg = adaptService.selectByPrimaryKey(topOrgId);
            map.put("org", cmuOrg);
            map.put("orgFun", defFunService.selectTopByOrg(topOrgId));
        }
        return new ResultTo().setData(map);
    }

    /**
     * 增加顶级机构
     *
     * @param cmuOrg
     * @param cmuUser
     * @param funIds
     * @return
     */
    @PostMapping("/top")
    @RequiresPermissions("post:/web/cmuOrg/top")
    public ResultTo insertTopOrg(CmuOrg cmuOrg, CmuUser cmuUser, String[] funIds, MultipartFile logoFile) {
        if (logoFile == null) {
            return new ResultTo(ResultEnum.PARAM_ERROR, "Logo不能为空");
        }
        cmuOrg.setParentId("0");
        ResultTo resultTo = validBuild(cmuOrg, false);
        if ((int) resultTo.get("code") == ResultEnum.OPERATION_FAILED.getCode()) {
            return resultTo;
        }
        orgService.insertTopOrg(cmuOrg, cmuUser, funIds, logoFile);
        return new ResultTo();
    }

    /**
     * 更新顶级机构
     *
     * @param cmuOrg
     * @param funIds
     * @param logoFile
     * @return
     */
    @PutMapping("/top")
    @RequiresPermissions("put:/web/cmuOrg/top")
    public ResultTo updateTopOrg(CmuOrg cmuOrg, String[] funIds, MultipartFile logoFile) {
        cmuOrg.setParentId("0");
        ResultTo resultTo = validBuild(cmuOrg, true);
        if ((int) resultTo.get("code") == ResultEnum.OPERATION_FAILED.getCode()) {
            return resultTo;
        }
        orgService.updateTopOrg(cmuOrg, funIds, logoFile);
        return new ResultTo();
    }

    /**
     * 删除顶级机构
     *
     * @param topOrgId
     * @return
     */
    @DeleteMapping("/{topOrgId}/top")
    @RequiresPermissions("delete:/web/cmuOrg/topOrgId/top")
    public ResultTo deleteTopOrg(@PathVariable String topOrgId) {
        return new ResultTo();
    }


    @PostMapping("/valid")
    @RequiresUser
    public ResultTo valid(CmuOrg cmuOrg, @RequestParam(defaultValue = "false") boolean isUpdate) {
        return validBuild(cmuOrg, isUpdate);
    }

    private ResultTo validBuild(CmuOrg org, boolean isUpdate) {
        CmuOrg cmuOrg = new CmuOrg();
        int selectCount;
        CmuOrg cmuOrgOne = new CmuOrg();
        if (isUpdate) {
            cmuOrgOne = orgService.selectByPrimaryKey(org.getId());
        }
        if (StringUtils.isNotBlank(org.getName())) {
            if (isUpdate) {
                if (!cmuOrgOne.getName().equals(org.getName())) {
                    cmuOrg.setName(org.getName());
                    cmuOrg.setParentId(org.getParentId());
                    selectCount = orgService.selectCount(cmuOrg);
                    if (selectCount != 0) {
                        return new ResultTo(ResultEnum.OPERATION_FAILED, "机构名已经存在");
                    }
                }
            } else {
                cmuOrg.setName(org.getName());
                cmuOrg.setParentId(org.getParentId());
                selectCount = orgService.selectCount(cmuOrg);
                if (selectCount != 0) {
                    return new ResultTo(ResultEnum.OPERATION_FAILED, "机构名已经存在");
                }
            }
        }
        if (StringUtils.isNotBlank(org.getCreditCode())) {
            if (isUpdate) {
                if (!cmuOrgOne.getCreditCode().equals(org.getCreditCode())) {
                    cmuOrg.setCreditCode(org.getCreditCode());
                    cmuOrg.setName(null);
                    selectCount = orgService.selectCount(cmuOrg);
                    if (selectCount != 0) {
                        return new ResultTo(ResultEnum.OPERATION_FAILED, "机构统一社会信用代码已经存在");
                    }
                }
            } else {
                cmuOrg.setCreditCode(org.getCreditCode());
                cmuOrg.setName(null);
                selectCount = orgService.selectCount(cmuOrg);
                if (selectCount != 0) {
                    return new ResultTo(ResultEnum.OPERATION_FAILED, "机构统一社会信用代码已经存在");
                }
            }
        }
        if (StringUtils.isNotBlank(org.getOrgContact())) {
            if (isUpdate) {
                if (!cmuOrgOne.getOrgContact().equals(org.getOrgContact())) {
                    cmuOrg.setOrgContact(org.getOrgContact());
                    cmuOrg.setCreditCode(null);
                    selectCount = orgService.selectCount(cmuOrg);
                    if (selectCount != 0) {
                        return new ResultTo(ResultEnum.OPERATION_FAILED, "机构联系方式已存在");
                    }
                }
            } else {
                cmuOrg.setOrgContact(org.getOrgContact());
                cmuOrg.setCreditCode(null);
                selectCount = orgService.selectCount(cmuOrg);
                if (selectCount != 0) {
                    return new ResultTo(ResultEnum.OPERATION_FAILED, "机构联系方式已存在");
                }
            }
        }
        return new ResultTo();
    }
}
